/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.frameworks.core.batterystatsloadtests;

import static org.junit.Assert.assertNotNull;

import android.app.Instrumentation;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.BatteryConsumer;

import androidx.test.platform.app.InstrumentationRegistry;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

public class SystemServiceCallLoadTest {
    private static final String TAG = "SystemServiceCallLoadTest";
    private static final int TIMEOUT_MILLIS = 60 * 60 * 1000;
    private static final float BATTERY_DRAIN_THRESHOLD_PCT = 2.99f;

    @Rule
    public PowerMetricsCollector mPowerMetricsCollector = new PowerMetricsCollector(TAG,
            BATTERY_DRAIN_THRESHOLD_PCT, TIMEOUT_MILLIS);

    private PackageManager mPackageManager;

    @Before
    public void setup() {
        Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
        mPackageManager = instrumentation.getContext().getPackageManager();
    }

    @Test
    public void test() {
        while (mPowerMetricsCollector.checkpoint()) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse("http://example.com/"), "text/plain");
            intent.addCategory(Intent.CATEGORY_BROWSABLE);
            ResolveInfo resolveInfo = mPackageManager.resolveActivity(intent, 0);
            assertNotNull(resolveInfo);
        }

        mPowerMetricsCollector.reportMetrics();

        mPowerMetricsCollector.report(
                "Total system server calls made: " + mPowerMetricsCollector.getIterationCount());

        mPowerMetricsCollector.reportMetricAsPercentageOfDrainedPower(
                BatteryConsumer.POWER_COMPONENT_SYSTEM_SERVICES);
    }
}
